package com.chagee.store.operation.server.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.chagee.store.operation.api.enums.PushFinanceStatusEnum;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.model.bo.ExportOrderEmailBO;
import com.chagee.store.operation.server.service.biz.StoreSettlementBizService;
import com.chagee.store.operation.server.utils.DateUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 推送财务系统
 * @Author : hk
 * @Date : 2025/1/13
 */

@Component
@Slf4j
public class PushFinanceJobHandler {


	@Resource
	private StoreSettlementBizService storeSettlementBizService;

	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;


	/**
	 *
	 * 凌晨一点 : 0 0 1 * * ?
	 * 推送财务未推送, 推送失败的单子
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("pushFinanceSettlement")
	public ReturnT<String> pushFinanceSettlementMsg(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = cn.hutool.core.date.DateUtil.timer();
		log.info("推送财务发票信息定时任务开始,traceId :{}", span.getTraceId());
		try {
			if (StringUtils.isNotBlank(param)) {
				//结算单号
				List<String> settlementNos = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.batchSelectSettlement(settlementNos);
				pushFinance(storeSettlementDOS);
			}else {
				long startIndex = 0L;
				while (true) {
					List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.selectSettlements(startIndex);
					if (CollectionUtils.isEmpty(storeSettlementDOS)) {
						break;
					}
					log.info("推送财务发票信息 :{}", JSON.toJSONString(storeSettlementDOS));
					List<StoreSettlementDO> settlementDOS = storeSettlementDOS.stream().filter(s -> StringUtils.isNotBlank(s.getInvoice())).collect(Collectors.toList());
					if (CollectionUtil.isNotEmpty(settlementDOS)) {
						pushFinance(settlementDOS);
					}

					startIndex = Math.toIntExact(storeSettlementDOS.stream().map(StoreSettlementDO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}

		} catch (Exception e) {
			XxlJobLogger.log("财务发票信息定时任务异常，异常信息:", e);
			log.error("财务发票信息定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("财务发票信息定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}

	private void pushFinance(List<StoreSettlementDO> storeSettlementDOS) {
		for (StoreSettlementDO entry : storeSettlementDOS) {
			PushFinanceStatusEnum pushStatus = PushFinanceStatusEnum.SUCCESS;
			//推送财务系统
			try {
				storeSettlementBizService.pushFinance(entry);
				log.info("结算单{}推送财务发票信息成功", JSON.toJSONString(entry.getSettlementNo()));
			} catch (Exception e) {
				pushStatus = PushFinanceStatusEnum.FAILURE;
				log.error("结算单{}推送财务系统失败", entry.getSettlementNo(), e);
			}
			storeSettlementBaseService.updateSettlement(entry.getSettlementNo(), pushStatus.getType());

		}
	}

}
